package io.gitee.hechenl.fastiotreport.controller;

import io.gitee.hechenl.fastiotreport.controller.converter.ConfigMetricConverter;
import io.gitee.hechenl.fastiotreport.controller.validator.ConfigMetricValidator;
import io.gitee.hechenl.fastiotreport.domain.dto.ConfigMetricUpSertDTO;
import io.gitee.hechenl.fastiotreport.domain.model.ConfigMetric;
import io.gitee.hechenl.fastiotreport.domain.model.ConfigMetricGroup;
import io.gitee.hechenl.fastiotreport.domain.model.ConfigPoint;
import io.gitee.hechenl.fastiotreport.domain.vo.ConfigMetricListVO;
import io.gitee.hechenl.fastiotreport.domain.vo.ViewOptionsVO;
import io.gitee.hechenl.fastiotreport.service.IConfigMetricGroupService;
import io.gitee.hechenl.fastiotreport.service.IConfigMetricService;
import io.gitee.hechenl.fastiotreport.service.IConfigPointService;
import io.gitee.hechenl.fastiotreport.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


@RequestMapping("/config/metric")
@RestController
public class ConfigMetricController {

    @Autowired
    private IConfigMetricService configMetricService;
    @Autowired
    private IConfigMetricGroupService configMetricGroupService;
    @Autowired
    private IConfigPointService configPointService;


    private String getComment(String input) {
        int firstSlashIndex = input.indexOf('/');
        String beforeSlash = input.substring(0, firstSlashIndex);

        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(beforeSlash);

        StringBuffer result = new StringBuffer();
        while (matcher.find()) {
            ConfigPoint configPoint = configPointService.list(matcher.group());
            if (configPoint == null) {
                throw new RuntimeException("数据点未导入：" + matcher.group());
            }
            matcher.appendReplacement(result, configPoint.getPointName());
        }
        matcher.appendTail(result);
        return result.toString();
    }

    @PostMapping("/insertOrUpdate")
    public Result<Void> insertOrUpdate(@RequestBody ConfigMetricUpSertDTO dto) {
        ConfigMetricValidator.validInsertOrUpdate(dto);
        String comment = getComment(dto.getMetricExpr());
        ConfigMetric config = ConfigMetricConverter.toModelList(dto, comment);
        configMetricService.insertOrUpdate(config);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<List<ConfigMetricListVO>> list() {
        return Result.success(ConfigMetricConverter.toVOList(configMetricService.list()));
    }

    @GetMapping("/group/list")
    public Result<List<ViewOptionsVO>> metricGroupList() {
        List<ConfigMetricGroup> list = configMetricGroupService.list();
        return Result.success(ConfigMetricConverter.toViewOptionsVOList(list));
    }

}
